document.addEventListener('DOMContentLoaded', function() {//dom内容加载完成后执行
	// 检查登录状态并更新导航栏
	updateUserInfo();

	// 初始化地理位置权限控制
	initLocationPermission();

	// 加载评论
	loadComments();

	// 评论表单提交处理
	document.getElementById('commentForm').addEventListener('submit', function(e) {
		e.preventDefault();//阻止表单默认提交行为
		submitComment();//调用提交表单评论函数
	});

	// 媒体上传预览
	document.getElementById('mediaUpload').addEventListener('change', function(e) {
		previewMedia(e.target.files);//预览上传的媒体文件
	});

	// 设置拖放区域
	setupDragAndDrop();
});

// 设置拖放区域
function setupDragAndDrop() {
	const mediaPreview = document.getElementById('media-preview');
	const dropZone = document.querySelector('.comment_form');

	// 防止默认拖放行为
	['dragenter', 'dragover', 'dragleave', 'drop'].forEach(eventName => {
		dropZone.addEventListener(eventName, preventDefaults, false);
		document.addEventListener(eventName, preventDefaults, false);
	});

	// 高亮显示拖放区域
	['dragenter', 'dragover'].forEach(eventName => {
		dropZone.addEventListener(eventName, highlight, false);
	});

	['dragleave', 'drop'].forEach(eventName => {
		dropZone.addEventListener(eventName, unhighlight, false);
	});

	// 处理文件拖放
	dropZone.addEventListener('drop', handleDrop, false);

	// 全局拖拽事件
	document.addEventListener('dragover', function(e) {
		e.preventDefault();
		// 检查是否正在拖拽预览项
		const draggingItem = document.querySelector('.media-item-container[dragging]');
		if (draggingItem) {
			e.dataTransfer.dropEffect = 'move';
		}
	});

	document.addEventListener('drop', function(e) {
		e.preventDefault();
		const draggingItem = document.querySelector('.media-item-container[dragging]');
		if (!draggingItem) return;

		// 检查是否拖到了其他预览项上，isInsideAnyItem用于判断当前拖拽释放位置是否位于任何其他媒体预览项的内部。
		const previewItems = document.querySelectorAll('.media-item-container:not([dragging])');
		let isInsideAnyItem = false;// 初始设为false，假设不在任何项内

		previewItems.forEach(item => {
			const rect = item.getBoundingClientRect();// 获取每个预览项的坐标信息
			if (
				e.clientX >= rect.left &&
				e.clientX <= rect.right &&
				e.clientY >= rect.top &&
				e.clientY <= rect.bottom
			) {
				isInsideAnyItem = true;
			}
		});

		// 只有当拖拽释放位置不在任何预览项内时才删除被拖拽的项
		if (!isInsideAnyItem) {
			// 从 currentMediaFiles 中移除对应的文件
			const fileId = draggingItem.dataset.fileId;
			currentMediaFiles = currentMediaFiles.filter(f => f.id !== fileId);//调用数组的 filter 方法，遍历数组中的每个元素
			draggingItem.remove();
		}

		// 移除拖拽状态
		draggingItem.removeAttribute('dragging');
	});
	
	//阻止默认事件
	function preventDefaults(e) {
		e.preventDefault();
		e.stopPropagation();
	}
	//高亮显示拖放区域
	function highlight() {
		dropZone.classList.add('highlight');
	}
	//取消高亮显示
	function unhighlight() {
		dropZone.classList.remove('highlight');
	}
	//处理文件拖放
	function handleDrop(e) {
		const dt = e.dataTransfer;
		const files = dt.files;
		// 如果是内部拖拽，直接返回
		if (document.querySelector('.media-item-container[dragging]')) {
		    return;
		}

		// 检查所有文件是否都是图片
		const invalidFiles = Array.from(files).filter(file => !file.type.startsWith('image/'));
		if (invalidFiles.length > 0) {
			alert('只允许上传图片文件 (JPEG, PNG, GIF等)');
			return;
		}

		if (files.length > 0) {
			previewMedia(files);
		}
	}
}


// 更新用户信息显示
function updateUserInfo() {
	const currentUser = JSON.parse(localStorage.getItem('currentUser'));
	const loginLink = document.getElementById('login-link');
	const userProfile = document.getElementById('user-profile');
	const userAvatar = document.getElementById('user-avatar');
	const usernamelink = document.getElementById('username');

	if (currentUser) {// 用户已登录
		loginLink.style.display = 'none';
		userProfile.style.display = 'flex';
		usernamelink.textContent = currentUser.username;

		if (currentUser.avatar) {// 显示用户头像
			userAvatar.src = currentUser.avatar;
			userAvatar.style.display = 'block';
		} else {// 没有头像时隐藏头像元素
			userAvatar.style.display = 'none';
			usernamelink.style.marginLeft = '0.5em';
		}
	} else {// 用户未登录
		loginLink.style.display = 'inline';
		userProfile.style.display = 'none';
	}
}

// 初始化地理位置权限控制
function initLocationPermission() {
	const locationCheckbox = document.getElementById('location-permission');
	const locationInfo = document.getElementById('location-info');

	locationCheckbox.addEventListener('change', function() {
		if (this.checked) {
			if (navigator.geolocation) {
				navigator.geolocation.getCurrentPosition(
					(position) => {
						const {
							latitude,
							longitude
						} = position.coords;

						// 存储原始经纬度
						locationInfo.dataset.latitude = latitude.toFixed(6);
						locationInfo.dataset.longitude = longitude.toFixed(6);

						// 调用腾讯地图API获取地址
						const callbackName = `tencentCallback_${Date.now()}`;
						window[callbackName] = (response) => {
							// 清理资源
							document.body.removeChild(script);
							delete window[callbackName];

							if (response.status === 0) {
								// 成功获取地址
								const address = response.result.address;
								const poi = response.result.pois?. [0]?.title || '';
								locationInfo.textContent = `位置: ${address} ${poi}`;
								locationInfo.dataset.address = address;
							} else {
								// 失败时显示经纬度
								locationInfo.textContent =
									`位置: 纬度${latitude.toFixed(6)}, 经度${longitude.toFixed(6)}`;
								locationInfo.dataset.address = '';
							}
							locationInfo.style.display = 'inline';
						};

						// 发起JSONP请求
						const script = document.createElement('script');
						const key = 'KHHBZ-BM2Y4-NZJUO-KXUIY-R5KWQ-BYBP4';
						script.src =
							`https://apis.map.qq.com/ws/geocoder/v1/?location=${latitude},${longitude}&key=${key}&output=jsonp&callback=${callbackName}`;
						document.body.appendChild(script);
					},
					(error) => {
						this.checked = false;
						alert('您已拒绝共享位置信息');
						locationInfo.style.display = 'none';
					}
				);
			} else {
				this.checked = false;
				alert('您的浏览器不支持地理位置功能');
				locationInfo.style.display = 'none';
			}
		} else {
			locationInfo.style.display = 'none';
			delete locationInfo.dataset.latitude;
			delete locationInfo.dataset.longitude;
			delete locationInfo.dataset.address;
		}
	});
}



// 全局变量存储当前预览的文件
let currentMediaFiles = [];

// 预览上传的媒体文件
function previewMedia(files) {
    const mediaPreview = document.getElementById('media-preview');
    
    Array.from(files).forEach(file => {
        if (!file.type.startsWith('image/')) {
            alert('只允许上传图片文件 (JPEG, PNG, GIF等)');
            return;
        }
        
        // 为每个文件生成唯一ID
        const fileId = 'file-' + Date.now() + '-' + Math.random().toString(36).substr(2, 9);
        
        const reader = new FileReader();
        reader.onload = function(e) {
            const container = document.createElement('div');
            container.className = 'media-item-container';
            container.dataset.fileId = fileId; // 使用唯一ID关联
            
            const mediaItem = document.createElement('img');
            mediaItem.src = e.target.result;
            mediaItem.className = 'media-item';

			// 添加删除按钮
            const deleteBtn = document.createElement('span');
            deleteBtn.className = 'delete-media';
            deleteBtn.innerHTML = '&times;';
            deleteBtn.title = '删除';
            deleteBtn.addEventListener('click', function() {
                // 根据fileId删除对应的文件
                currentMediaFiles = currentMediaFiles.filter(f => f.id !== fileId);
                container.remove();
            });

			// 添加拖拽删除支持
            container.draggable = true;
            container.addEventListener('dragstart', function(e) {
                this.setAttribute('dragging', 'true');
                e.dataTransfer.setData('text/plain', 'delete');
                e.dataTransfer.effectAllowed = 'move';
            });

            container.addEventListener('dragend', function() {
                this.removeAttribute('dragging');
            });

            container.appendChild(mediaItem);
            container.appendChild(deleteBtn);
            mediaPreview.appendChild(container);

            // 添加文件到数组时带上唯一ID
            currentMediaFiles.push({
                id: fileId,
                file: file
            });
        };
        reader.readAsDataURL(file);
    });
    document.getElementById('mediaUpload').value = '';
}
// fileInput.addEventListener('change', () => {
//     if (fileInput.files.length > 0) {
//         previewMedia(fileInput.files);
//         fileInput.value = '';
//     }
// });

// 提交评论
function submitComment() {
    const currentUser = JSON.parse(localStorage.getItem('currentUser'));
    if (!currentUser) {
        alert('请先登录后再发表评论');
        return;
    }

    const commentText = document.getElementById('commentText').value.trim();
    const locationInfo = document.getElementById('location-info');
    const locationPermission = document.getElementById('location-permission').checked;

    if (!commentText && currentMediaFiles.length === 0) {
        alert('评论内容或媒体文件不能为空');
        return;
    }

    // 重置currentMediaFiles，只保留实际存在的预览项对应的文件
    const existingFileIds = Array.from(document.querySelectorAll('.media-item-container')).map(el => el.dataset.fileId);
    currentMediaFiles = currentMediaFiles.filter(f => existingFileIds.includes(f.id));

    const mediaData = [];
    if (currentMediaFiles.length > 0) {
        currentMediaFiles.forEach(item => {
            const reader = new FileReader();
            reader.onload = function(e) {
                mediaData.push({
                    type: 'image',
                    data: e.target.result
                });

                if (mediaData.length === currentMediaFiles.length) {
                    saveComment(commentText, mediaData, locationPermission ? locationInfo : null);
                }
            };
            reader.readAsDataURL(item.file);
        });
    } else {
        saveComment(commentText, [], locationPermission ? locationInfo : null);
    }
}

// 保存评论到localStorage
function saveComment(text, media, locationElement) {
	const comments = JSON.parse(localStorage.getItem('comments')) || [];
	const currentUser = JSON.parse(localStorage.getItem('currentUser'));

	const newComment = {
		id: Date.now(),
		userId: currentUser.username,
		userAvatar: currentUser.avatar || null,
		text: text,
		media: media,
		location: locationElement ? {
			text: locationElement.textContent,
			address: locationElement.dataset.address || '',
			latitude: locationElement.dataset.latitude || '',
			longitude: locationElement.dataset.longitude || ''
		} : null,
		timestamp: new Date().toISOString(),
		likes: 0,
		dislikes: 0
	};

	// 将新评论添加到数组开头
	comments.unshift(newComment);
	localStorage.setItem('comments', JSON.stringify(comments));

	// 重置表单
	document.getElementById('commentForm').reset();
	document.getElementById('media-preview').innerHTML = '';
	document.getElementById('location-permission').checked = false;
	document.getElementById('location-info').style.display = 'none';
	currentMediaFiles = []; // 清空媒体文件数组

	// 重新加载评论
	loadComments();
}

// 加载评论
function loadComments() {
	const comments = JSON.parse(localStorage.getItem('comments')) || [];
	const commentList = document.getElementById('commentList');
	commentList.innerHTML = '';

	comments.forEach(comment => {
		const commentItem = document.createElement('div');
		commentItem.className = 'comment_item';
		commentItem.dataset.id = comment.id;

		// 用户头像
		const avatarDiv = document.createElement('div');
		avatarDiv.className = 'comment_avatar';
		if (comment.userAvatar) {
			const avatarImg = document.createElement('img');
			avatarImg.src = comment.userAvatar;
			avatarDiv.appendChild(avatarImg);
		} else {
			avatarDiv.textContent = '👤';
		}

		// 评论内容
		const contentDiv = document.createElement('div');
		contentDiv.className = 'comment_content';

		// 评论头部（用户名和时间）
		const headerDiv = document.createElement('div');
		headerDiv.className = 'comment_header';

		const authorSpan = document.createElement('span');
		authorSpan.className = 'comment_author';
		authorSpan.textContent = comment.userId;

		const timeSpan = document.createElement('span');
		timeSpan.className = 'comment_time';
		timeSpan.textContent = new Date(comment.timestamp).toLocaleString();

		headerDiv.appendChild(authorSpan);
		headerDiv.appendChild(timeSpan);

		// 评论文本
		const textDiv = document.createElement('div');
		textDiv.className = 'comment_text';
		textDiv.textContent = comment.text;

		// 评论媒体
		const mediaDiv = document.createElement('div');
		mediaDiv.className = 'comment_media';
		comment.media.forEach(media => {
			let mediaElement;
			if (media.type === 'image') {
				mediaElement = document.createElement('img');
				mediaElement.src = media.data;
			}
			mediaDiv.appendChild(mediaElement);
		});

		// 评论位置
		const locationDiv = document.createElement('div');
		locationDiv.className = 'comment_location';
		if (comment.location) {
			locationDiv.textContent = comment.location.text;
		}

		// 评论操作（点赞/点踩）
		const actionsDiv = document.createElement('div');
		actionsDiv.className = 'comment_actions';

		const likeAction = document.createElement('div');
		likeAction.className = 'comment_action like-action';
		likeAction.innerHTML = `<span>👍</span> <span class="like-count">${comment.likes}</span>`;
		likeAction.addEventListener('click', () => {
			comment.likes++;
			updateComment(comment.id, {
				likes: comment.likes
			});
		});

		const dislikeAction = document.createElement('div');
		dislikeAction.className = 'comment_action dislike-action';
		dislikeAction.innerHTML = `<span>👎</span> <span class="dislike-count">${comment.dislikes}</span>`;
		dislikeAction.addEventListener('click', () => {
			comment.dislikes++;
			updateComment(comment.id, {
				dislikes: comment.dislikes
			});
		});

		actionsDiv.appendChild(likeAction);
		actionsDiv.appendChild(dislikeAction);

		// 组装评论内容
		contentDiv.appendChild(headerDiv);
		contentDiv.appendChild(textDiv);
		if (comment.media.length > 0) contentDiv.appendChild(mediaDiv);
		if (comment.location) contentDiv.appendChild(locationDiv);
		contentDiv.appendChild(actionsDiv);

		// 组装评论项
		commentItem.appendChild(avatarDiv);
		commentItem.appendChild(contentDiv);

		commentList.appendChild(commentItem);
	});
}

// 更新评论（点赞/点踩）
function updateComment(commentId, updates) {
	const comments = JSON.parse(localStorage.getItem('comments')) || [];
	const commentIndex = comments.findIndex(c => c.id === commentId);

	if (commentIndex !== -1) {
		comments[commentIndex] = {
			...comments[commentIndex],
			...updates
		};
		localStorage.setItem('comments', JSON.stringify(comments));

		// 更新UI
		const likeCount = document.querySelector(`.comment_item[data-id="${commentId}"] .like-count`);
		const dislikeCount = document.querySelector(`.comment_item[data-id="${commentId}"] .dislike-count`);

		if (likeCount) likeCount.textContent = comments[commentIndex].likes;
		if (dislikeCount) dislikeCount.textContent = comments[commentIndex].dislikes;
	}
}
// 添加iframe游戏胜利监听
// window.addEventListener('message', function(event) {
//     if (event.data.type === 'playerWin') {
//         // 调用排行榜的添加记录函数
//         const { username, avatar } = event.data;
//         addWinRecord(username, avatar);
//     }
// });

// 将addWinRecord函数暴露给全局
// window.addWinRecord = function(username, avatar) {
//     const leaderboardData = JSON.parse(localStorage.getItem('badmintonLeaderboard')) || [];
//     const existingUserIndex = leaderboardData.findIndex(user => user.username === username);
    
//     if (existingUserIndex !== -1) {
//         leaderboardData[existingUserIndex].wins++;
//         leaderboardData[existingUserIndex].timestamp = new Date().toISOString();
//     } else {
//         leaderboardData.push({
//             username,
//             avatar,
//             wins: 1,
//             timestamp: new Date().toISOString()
//         });
//     }
    
//     leaderboardData.sort((a, b) => b.wins - a.wins);
//     localStorage.setItem('badmintonLeaderboard', JSON.stringify(leaderboardData));
// };